/**
 * 将阿拉伯数字转化为汉字
 * @param {num} section 阿拉伯数字
 */
function getChineseNum(section) {
  const chnNumChar = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
  const chnUnitChar = ['', '十', '百', '千', '万', '亿', '万亿', '亿亿'];
  let strIns = '', chnStr = '';
  let unitPos = 0;
  let zero = true;
  while (section > 0) {
    const v = section % 10;
    if (v === 0) {
      if (!zero) {
        zero = true;
        chnStr = chnNumChar[v] + chnStr;
      }
    } else {
      zero = false;
      strIns = chnNumChar[v];
      strIns += chnUnitChar[unitPos];
      chnStr = strIns + chnStr;
    }
    unitPos++;
    section = Math.floor(section / 10);
  }
  return chnStr;
}

/**
 * 根据身份证号获取出生年月和性别
 * @param {num} card 身份证号
 */
function getAnalysisIdCard(card, num) {
  if (num == 1) {
    //获取出生日期
    let birth = card.substring(6, 10) + "-" + card.substring(10, 12) + "-" + card.substring(12, 14);
    return birth;
  }
  if (num == 2) {
    //获取性别
    if (parseInt(card.substr(16, 1)) % 2 == 1) {
      //男
      return "男";
    } else {
      //女
      return "女";
    }
  }
  if (num == 3) {
    //获取年龄
    var myDate = new Date();
    var month = myDate.getMonth() + 1;
    var day = myDate.getDate();
    var age = myDate.getFullYear() - card.substring(6, 10) - 1;
    if (card.substring(10, 12) < month || card.substring(10, 12) == month && card.substring(12, 14) <= day) {
      age++;
    }
    return age;
  }
}

//时间格式转换
function formatDate(fmt, mydate) {
  if (!mydate) return "";
  if (mydate.split(".").length) {
    mydate = mydate.split(".")[0]
  }
  var dateformat = mydate.replace(/T/g, " "),
    mydate = new Date(dateformat.replace(/-/g, "/"));
  //var mydate = new Date(mydate);
  var o = {
    "Y+": mydate.getFullYear(),
    "M+": mydate.getMonth() + 1, //月份
    "d+": mydate.getDate(), //日
    "h+": mydate.getHours(), //小时
    "m+": mydate.getMinutes(), //分
    "s+": mydate.getSeconds(), //秒
    "q+": Math.floor((mydate.getMonth() + 3) / 3), //季度
    S: mydate.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1);
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      //
      if (k == "Y+") {
        fmt = fmt.replace(RegExp.$1, o[k]);
      }
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1
          ? o[k]
          : ("00" + o[k]).substr(("" + o[k]).length)
      );
    }
  }
  return fmt;
}

export { getChineseNum, getAnalysisIdCard, formatDate }